<?php
/**
 * 用户注册api接口
 * @author Jmashimaro
 */
class MemberApp extends FrontendApp {

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 注册第一步先发送验证码
     * 手机短信验证
     */
    public function verify() {
        $action = '注册第一步先发送验证码,手机短信验证';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        /**过滤参数**/
        $phone_mob = $this->get_gp('phone_mob', 'G');

        /**验证手机号的合法性**/
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, '手机号码不能为空！');
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, '手机号码长度不是11位！');
        } elseif (!$this->is_number($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '非法的手机号码！');
        }

        /**生成四位随机数的验证码**/
        $verify_code = '';
        for ($i = 0; $i < 4; $i++) {
            $verify_code .= rand(0, 9);
        }

        /**连接短信日志记录中心**/
        $sms = ms('smslogs');

        /**获取手机短信日志信息**/
        $info = $this->get_sms_logs_info($phone_mob);

        /**如果存在手机号码，则更新验证信息**/
        if ($info['phone_mob']) {
            /**一分钟之内不能再次发送验证码**/
            if ((time() - $info['created_at']) < 60) {
                $this->ajax_return(FLAG_ERROR, "已经发送了短信验证码，请您稍后再试！");
            }

            /**当天发送的短信是否超过了十五条**/
            if ($info['count'] >= 5) {
                $this->ajax_return(FLAG_ERROR, "您当天发送的短信验证码已经超过了5条，请您明天再试！");
            }
        }

        $model = m('member');

        /**开启事务**/
        $model->begin();

        /**插入记录**/
        $flag  = $sms->user->verify($phone_mob, $verify_code);
        if (!$flag) {
            $model->rollback();
            $this->ajax_return(FLAG_ERROR, '发送短信失败，请您重试！');
        }

        /**发送手机验证码**/
        $content=array("template"=>"authcode","code"=>$verify_code);
        $rs = $sms->pm->rpcsms($phone_mob,$content);
        if ($rs['errcode'] != 0) {
            $model->rollback();
            $this->ajax_return(FLAG_ERROR, $rs['errmsg']);
        }
        /**提交事务**/
        $model->commit();

        $this->ajax_return(FLAG_OK, "发送短信验证码成功！");
    }


    /**
     * 用户注册
     */
    public function register() {
        $action = '用户注册';
        setLogParameter($action);
        /**登陆**/
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, "非法的请求！");
        }
        /**过滤参数**/
        $user_name      = $this->get_gp('user_name', 'P');
        $password       = $this->get_gp('password', 'P');
        $phone_mob      = $this->get_gp('phone_mob', 'P');
        $verify_code    = $this->get_gp('verify_code', 'P');
        $code           = $this->get_gp('code','P');
        /*
         * 验证图形验证码
         */
        /**验证码**/
        if (!$code) {
            $this->ajax_return(FLAG_ERROR, "验证码不能为空！");
        } elseif (!$this->is_number($code)) {
            $this->ajax_return(FLAG_ERROR, "验证码格式不正确！");
        } elseif (strlen($code) != 4) {
            $this->ajax_return(FLAG_ERROR, "请您输入四位正确的数字验证码！");
        }
        if($this->checkCode()!=$code){
            $this->ajax_return(FLAG_ERROR,"验证码不正确！");
        }

        /**用户名不能为空**/
        if (!$user_name) {
            $this->ajax_return(FLAG_ERROR, "用户名不能为空！");
        }
        /**密码不能为空**/
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, "密码不能为空！");
        } elseif (strlen($password) < 6) {
            $this->ajax_return(FLAG_ERROR, "密码长度不能少于六位！");
        }
        /**验证手机号**/
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, "手机号码不能为空！");
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, "请您输入正确的11位手机号码！");
        } elseif (!$this->is_number($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, "手机号码格式不正确！");
        }

        /**验证码**/
        if (!$verify_code) {
            $this->ajax_return(FLAG_ERROR, "验证码不能为空！");
        } elseif (!$this->is_number($verify_code)) {
            $this->ajax_return(FLAG_ERROR, "验证码格式不正确！");
        } elseif (strlen($verify_code) != 4) {
            $this->ajax_return(FLAG_ERROR, "请您输入四位正确的数字验证码！");
        }

        /**用户名是否唯一**/
        if (!$this->check_username($user_name)) {
            $this->ajax_return(FLAG_ERROR, '用户名已经存在！');
        }

        /**手机号码是否唯一**/
        if (!$this->check_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号码已经存在！');
        }

        /**获取手机短信日志信息**/
        $info = $this->get_sms_logs_info($phone_mob);

        /**是否存在用户手机号码信息**/
        if (!$info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '用户手机号码信息不存在！');
        }

        /**验证码是否一致**/
        if ($verify_code != $info['verify_code']) {
            $this->ajax_return(FLAG_ERROR, '短信验证码不正确，请您重新输入！');
        }

        /**验证码时间是否超过半个小时**/
        if ((time() - $info['created_at']) > 1800) {
            $this->ajax_return(FLAG_ERROR, '短信验证码已经超时，请您重新获取！');
        }

        /**连接用户中心**/
        $ms = ms('member');
        $flag = $ms->user->register($user_name, $password, $phone_mob);

        if ($flag) {
            $this->ajax_return(FLAG_OK, "注册成功！");
        } else {
            $this->ajax_return(FLAG_ERROR, "注册失败！");
        }
    }


    /**
     * 用户登陆
     * @see FrontendApp::login()
     */
    public function login() {
        $action = '用户登录';
        setLogParameter($action);
        $config = require ROOT_PATH.'/data/config.qiniu.php';
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }

        /**过滤参数**/
        $user_name = $this->get_gp('user_name', 'P');
        $password  = $this->get_gp('password', 'p');
        /**检测用户名**/
        if (!$user_name) {
            $this->ajax_return(FLAG_ERROR, '请您输入用户名！');
        }
        /**检测密码**/
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, '请您输入密码！');
        }
        /**获取用户信息**/
        $info = $this->get_member_info($user_name);
        $info['portrait'] = $info['portrait'] ? $config['qiniu_url'].$info['portrait'] : '';
        /**验证用户名**/
        if (!$info['user_name'] && !$info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '用户名不存在，请您重新输入！');
        }
        /**验证密码**/
        if (sha1(md5($password)) != sha1($info['password'])) {
            $this->ajax_return(FLAG_ERROR, '密码不正确！');
        }

        //token加密方法
        //$str = $info['user_id'].'-'.md5('self').'-'.sha1(md5(sha1($info['user_id']).sha1($info['user_name']).sha1($info['password'])));
        //$token = base64_encode($str);
        //生成唯一的token
        $model = m('member');
        $sql = "SELECT accessToken FROM ".DB_PREFIX."member WHERE user_id='".$info['user_id']."'";
        $tokenNow = $model->getRow($sql);
        if($tokenNow['accessToken'] != '') {
            $token = $tokenNow['accessToken'];
        } else {
            $token = $this->getToken(TOKEN);
            //把生成的token存到用户数据中
            $sql = "UPDATE ".DB_PREFIX."member SET accessToken='".$token."' WHERE user_id='".$info['user_id']."'";
            $flag = $model->query($sql);
        }
        unset($info['password'],$info['reg_time'],$info['last_login'],$info['last_ip'],$info['feed_config']);
        $data['token'] = $token;
        $data['info'] = $info;
        $this->ajax_return(FLAG_OK, '登陆成功！', $data);
    }

    /**
     * 第三方登陆
     * @author jyx
     * @date 2015/11/11
     */
    public function loginOther() {
        $action = '第三方登录';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $outer_id = $this->get_gp('usid', 'P');//获取微信的id
        $nickName = $this->get_gp('userName', 'P');//用户名
        $portrait = $this->get_gp('iconURL', 'P');//用户头像
        if (!$outer_id) {
            $this->ajax_return(FLAG_ERROR, '用户不存在！');
        }
        $model = m('member');
        //获取用户信息
        $sql = "SELECT user_id,outer_id,nickname,portrait,phone_mob FROM ".DB_PREFIX."member WHERE outer_id='{$outer_id}' LIMIT 1";
        $info = $model->getRow($sql);
        if ($info) {//如果存在,则更新信息
            $sql = "UPDATE ".DB_PREFIX."member SET nickname='{$nickName}',portrait='{$portrait}' WHERE user_id={$info['user_id']}";
            $flag = $model->query($sql);
        } else {//不存在则插入信息
            $sql = "INSERT INTO ".DB_PREFIX."member (outer_id,nickname,portrait) VALUES ('{$outer_id}','{$nickName}','{$portrait}')";
            $flag = $model->query($sql);
            $last_id = $model->insert_id();//获取最后插入的id
            $info['user_id'] = $last_id;
            $info['outer_id'] = $outer_id;
            $info['nickname'] = $nickName;
            $info['portrait'] = $portrait;
        }
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '登陆失败!');
        }
        //token加密方法
        //$str = $info['user_id'].'-'.md5('wx').'-'.sha1(md5(sha1($info['user_id']).sha1($info['outer_id']).sha1($info['nickname'])));
        //$token = base64_encode($str);
        $sql = "SELECT accessToken FROM ".DB_PREFIX."member WHERE user_id='".$info['user_id']."'";
        $tokenNow = $model->getRow($sql);
        if($tokenNow['accessToken'] != '') {
            $token = $tokenNow['accessToken'];
        } else {
            $token = $this->getToken(TOKEN);
            //把生成的token存到用户数据中
            $sql = "UPDATE ".DB_PREFIX."member SET accessToken='".$token."' WHERE user_id='".$info['user_id']."'";
            $flag = $model->query($sql);
        }
        $data['token'] = $token;
        //$data['token'] = $token;
        $data['info'] = $info;
        $this->ajax_return(FLAG_OK, '登陆成功！', $data);

    }

    /**
     * 修改密码
     * @author mashimaro
     * @date 2015/03/02
     */
    public function password() {
        $action = '修改密码';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        //$user_id = $this->get_gp('user_id', 'P');
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(FLAG_ERROR, '请您登陆！');
        }
        $old_pwd = $this->get_gp('old_pwd', 'P');
        $password = $this->get_gp('password', 'P');
        $pwd = $this->get_gp('pwd', 'P');
        $code           = $this->get_gp('code','P');
        /*
         * 验证图形验证码
         */
        /**验证码**/
        if (!$code) {
            $this->ajax_return(FLAG_ERROR, "验证码不能为空！");
        } elseif (!$this->is_number($code)) {
            $this->ajax_return(FLAG_ERROR, "验证码格式不正确！");
        } elseif (strlen($code) != 4) {
            $this->ajax_return(FLAG_ERROR, "请您输入四位正确的数字验证码！");
        }
        if($this->checkCode()!=$code){
            $this->ajax_return(FLAG_ERROR,"验证码不正确！");
        }
        
        if (!$old_pwd) {
            $this->ajax_return(FLAG_ERROR, '旧密码不能为空！');
        }
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, '密码不能为空！');
        }
        if ($password != $pwd) {
            $this->ajax_return(FLAG_ERROR, '密码不一致，请您重新输入！');
        }
        $model = m('member');
        $info = $model->get(array('conditions'=>"user_id={$user_id}"));
        if (!$info) {
            $this->ajax_return(FLAG_ERROR, '用户信息不存在！');
        } elseif ($info['password'] != md5($old_pwd)) {
            $this->ajax_return(FLAG_ERROR, '旧密码不正确！');
        }
        $flag = $model->edit($user_id, array('password'=>md5($password)));
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '修改密码失败！');
        }
        $this->ajax_return(FLAG_OK, '操作成功！');
    }


    /**
     * 找回密码，发送验证码
     * @author mashimaro
     * @date 2015/03/04
     */
    public function findPwdVerify () {
        $action = '找回密码,发送验证码';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $phone_mob = $this->get_gp('phone_mob', 'G');
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, '手机号不能为空！');
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, '手机号码长度为11位，请您重新输入！');
        } elseif (!$this->is_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号格式不正确！');
        }
        $info = $this->get_member_info_by_phone($phone_mob);
        if (!$info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '用户信息不存在！');
        }
        /**生成四位随机数的验证码**/
        $verify_code = '';
        for ($i = 0; $i < 4; $i++) {
            $verify_code .= rand(0, 9);
        }
        $sms = ms('smslogs');
        $sms_model = m('smslogs');
        //数据入库
        $flag = $sms_model->add(array('phone_mob'=>$phone_mob,'verify_code'=>$verify_code,'created_at'=>time()));
        if (!$flag) {
            $this->ajax_return(FLAG_ERROR, '存储数据信息失败！');
        }
        /**发送手机验证码**/
        $content=array("template"=>"authcode","code"=>$verify_code);
        $rs = $sms->pm->rpcsms($phone_mob,$content);
        if ($rs['errcode'] != 0) {
            $this->ajax_return(FLAG_ERROR, $rs['msg']);
        }
        $this->ajax_return(FLAG_OK, "发送短信验证码成功！");
    }


    /**
     * 忘记密码，修改信息
     * @author mashimaro
     * @date 2015/03/04
     */
    public function findPwd() {
        $action = '忘记密码，修改信息';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $phone_mob = $this->get_gp('phone_mob', 'P');
        $verify = $this->get_gp('verify_code', 'P');
        $password = $this->get_gp('password', 'P');
        $pwd = $this->get_gp('pwd', 'pwd');
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, '密码不能为空！');
        } elseif (strlen($password) < 6) {
            $this->ajax_return(FLAG_ERROR, '密码长度不能少于六位！');
        }
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, '手机号不能为空！');
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, '手机号码长度为11位，请您重新输入！');
        } elseif (!$this->is_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号格式不正确！');
        }
        $model = m('member');
        $sql = "SELECT sms_id,phone_mob,verify_code,created_at FROM ".DB_PREFIX."sms_logs WHERE phone_mob='{$phone_mob}' ORDER BY sms_id DESC LIMIT 1";
        $sms = $model->getRow($sql);
        if (!$verify) {
            $this->ajax_return(FLAG_ERROR, '验证码不能为空，请您重新输入！');
        } elseif (strlen($verify) != 4) {
            $this->ajax_return(FLAG_ERROR, '验证码长度为4位，请您重新输入！');
        } elseif (!$this->is_number($verify)) {
            $this->ajax_return(FLAG_ERROR, '验证码格式不正确，请您重新输入！');
        } elseif ($sms['verify_code'] != $verify) {
            $this->ajax_return(FLAG_ERROR, '非法的验证码，请您重新输入！');
        }
        //验证码超时，有效时间10分钟
        if (time() - $sms['created_at'] > 600) {
            $this->ajax_return(FLAG_ERROR, '验证码超时，请您重新获取！');
        }
        if (!$password) {
            $this->ajax_return(FLAG_ERROR, '密码不能为空，请您重新输入！');
        }
        if ($password != $pwd) {
            $this->ajax_return(FLAG_ERROR, '密码不一致，请您重新输入！');
        }

        //获取用户信息
        $sql = "SELECT user_id FROM ".DB_PREFIX."member WHERE phone_mob='{$phone_mob}'";
        $info = $model->getRow($sql);
        if (!$info['user_id']) {
            $this->ajax_return(FLAG_ERROR, '用户信息不存在！');
        }
        $sql = "UPDATE ".DB_PREFIX."member SET password='".md5($password)."' WHERE user_id={$info['user_id']}";
        $flag = $model->query($sql);
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '更新用户信息失败！');
        }
        $this->ajax_return(FLAG_OK, '修改密码成功！');
    }

    /**
     * 上传头像
     * @author mashimaro
     * @date 2015/02/28
     */
    public function uploadAvatar() {
        $action = '上传头像';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $config = require ROOT_PATH . '/data/config.qiniu.php';
        $user_id = $this->checkLogin();
        //$user_id = $user_id ? intval($user_id) : 0;
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您登陆！');
        }
        $file = $_FILES['file'];
        if ($file['error'] != UPLOAD_ERR_OK) {
            $this->ajax_return(FLAG_ERROR, '上传图片错误！');
        }
        import('uploader.lib');
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->addFile($file);

        //获取原来的头像信息
        $model = m('member');
        $info = $model->get(array(
            'conditions'    => "user_id={$user_id}",
            'fields'        => 'portrait',
        ));
        //七牛云上传图片
        $filename = $uploader->random_filename();
        //$filename = 'data/files/mall/portrait/'.date('Y').'/'.date('m').'/'.date('d').'/'.$filename.$user_id.'.gif';
        $filename = 'data/files/mall/portrait/'.date('Y').'/'.date('m').'/'.date('d').'/'.$filename.$user_id;
        if (!is_dir(dirname($filename))) {
            $res = @mkdir(dirname($filename), 0777, true);
            if ($res === false) {
                $this->ajax_return(FLAG_ERROR, '创建目录失败!');
            }
        }
        $rs = @move_uploaded_file($file['tmp_name'], ROOT_PATH.'/'.$filename);
        if ($rs === false) {
            $this->ajax_return(FLAG_ERROR, '移动图片失败!');
        }
        //更新头像信息
        $flag = $model->edit($user_id, array('portrait'=>$filename));
        if ($flag === false) {
            @unlink(ROOT_PATH.'/'.$filename);//如果上传不成功，则删除刚上传的头像
            $this->ajax_return(FLAG_ERROR, '更新头像数据信息失败');
        }
        //删除旧的头像图片
        @unlink(ROOT_PATH.'/'.$info['portrait']);
        $this->ajax_return(FLAG_OK, '', array('portrait'=>$config['qiniu_url'].$filename));
    }

    /**
     * 绑定手机发送验证码
     * @author jyx
     * @date 2015/12/22
     */
    public function getBindPhoneCode() {
        $action = '绑定手机发送验证码';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $phone_mob = $this->get_gp('phone_mob', 'G');
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, '手机号不能为空！');
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, '手机号码长度为11位，请您重新输入！');
        } elseif (!$this->is_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号格式不正确！');
        }
        $model = m('member');
        //获取用户信息
        $sql = "SELECT phone_mob FROM ".DB_PREFIX."member WHERE phone_mob='{$phone_mob}' LIMIT 1";
        $info = $model->getRow($sql);
        if ($info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '此手机号已经被使用！');
        }
        /**生成四位随机数的验证码**/
        $verify_code = '';
        for ($i = 0; $i < 4; $i++) {
            $verify_code .= rand(0, 9);
        }
        //数据入库
        $time = time();
        $sql = "INSERT INTO ".DB_PREFIX."sms_logs (phone_mob,verify_code,created_at) VALUES ('{$phone_mob}','{$verify_code}',{$time})";
        $flag = $model->query($sql);
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '存储数据信息失败！');
        }
        /**发送手机验证码**/
        $sms = ms('smslogs');
        $content=array("template"=>"authcode","code"=>$verify_code);
        $rs = $sms->pm->rpcsms($phone_mob,$content);
        if ($rs['errcode'] != 0) {
            $this->ajax_return(FLAG_ERROR, $rs['msg']);
        }
        $this->ajax_return(FLAG_OK, "发送短信验证码成功！");
    }

    /**
     * 绑定手机
     * @author jyx
     * @date 2015/12/22
     */
    public function bindPhone() {
        $action = '绑定手机';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $usid = $this->get_gp('usid', 'P');
        $phone_mob = $this->get_gp('phone_mob', 'P');
        $verify_code = $this->get_gp('verify_code', 'P');
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, '手机号不能为空！');
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, '手机号码长度为11位，请您重新输入！');
        } elseif (!$this->is_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号格式不正确！');
        }
        if (!$verify_code) {
            $this->ajax_return(FLAG_ERROR, '验证码不能为空，请您重新输入！');
        }
        $model = m('member');
        //获取验证码信息
        $sql = "SELECT sms_id,phone_mob,verify_code,created_at FROM ".DB_PREFIX."sms_logs WHERE phone_mob='{$phone_mob}' ORDER BY sms_id DESC LIMIT 1";
        $sms = $model->getRow($sql);
        if (strlen($verify_code) != 4) {
            $this->ajax_return(FLAG_ERROR, '验证码长度为4位，请您重新输入！');
        } elseif (!$this->is_number($verify_code)) {
            $this->ajax_return(FLAG_ERROR, '验证码格式不正确，请您重新输入！');
        } elseif ($sms['verify_code'] != $verify_code) {
            $this->ajax_return(FLAG_ERROR, '非法的验证码，请您重新输入！');
        }
        //验证码超时，有效时间10分钟
        if (time() - $sms['created_at'] > 600) {
            $this->ajax_return(FLAG_ERROR, '验证码超时，请您重新获取！');
        }
        //获取用户信息
        $sql = "SELECT user_id,phone_mob FROM ".DB_PREFIX."member WHERE outer_id='{$usid}' LIMIT 1";
        $info = $model->getRow($sql);
        if (!$info) {
            $this->ajax_return(FLAG_ERROR, '用户信息不存在！');
        } elseif ($info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '您已经绑定了手机号码！');
        }
        //绑定手机
        $sql = "UPDATE ".DB_PREFIX."member SET phone_mob='{$phone_mob}' WHERE user_id={$info['user_id']}";
        $flag = $model->query($sql);
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '绑定手机失败！');
        }
        $this->ajax_return(FLAG_OK, '');
    }

    /**
     * 获取验证码
     * @author lz
     * @date 2016-1-6
     */
    public function getVerifyCode(){
        $action = '获取验证码';
        setLogParameter($action);
        $this->check_method('GET');
        $model = m('member');
        $data = $model->verifycode();
        $datas[] =$data;
        if($data){
            $this->ajax_return(FLAG_OK,'',$datas);
        }else{
            $this->ajax_return(FLAG_ERROR,'获取验证码失败！');
        }
    }
    public function getCode(){
        $data = array();
        $data['address'] = 'http://vpn-api.ios.herxi.com/index.php?app=member&act=getVerifyCode';
        $this->ajax_return(FLAG_OK, '',$data);
    }

    /**
     * 获取个人列表信息
     * @author lz
     * @date 2016-1-6
     */
    public function memberInfo(){
        $action = '获取个人列表信息';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }
        /* 取得列表数据 */
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！',array('user_id',$user_id));
        }
        $model = m('member');
        //获取个人列表信息
        $sql = "SELECT
                  user_name,gender,birthday,phone_mob,profession,description,banner,portrait
                FROM ".DB_PREFIX."member WHERE user_id=".$user_id;
        $info = $model->getRow($sql);
        if ($info) {
            $info['user_id'] = $user_id;
            $info['birthday'] = $info['birthday']?date('Y-m-d',$info['birthday']):'';
            $info['portrait'] = $info['portrait']?QINIU_URL.$info['portrait']:'';
            $info['banner'] = $info['banner']?QINIU_URL.$info['banner']:'';
            $this->ajax_return(FLAG_OK,"",array($info));
        } else {
            $this->ajax_return(FLAG_ERROR, '获取用户信息失败！');
        }
    }

    /**
     *修改手机号码
     * @author lz
     * @date 2016-1-6
     */
    public function editPhone(){
        $action = '修改手机号码';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }

        /* 取得列表数据 */
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！');
        }

        $phone_mob = $this->get_gp('phone_mob', 'P');
        $verify_code = $this->get_gp('verify_code', 'P');

        /**验证手机号**/
        if (!$phone_mob) {
            $this->ajax_return(FLAG_ERROR, "手机号码不能为空！");
        } elseif (strlen($phone_mob) != 11) {
            $this->ajax_return(FLAG_ERROR, "请您输入正确的11位手机号码！");
        } elseif (!$this->is_number($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, "手机号码格式不正确！");
        }

        /**验证码**/
        if (!$verify_code) {
            $this->ajax_return(FLAG_ERROR, "验证码不能为空！");
        } elseif (!$this->is_number($verify_code)) {
            $this->ajax_return(FLAG_ERROR, "验证码格式不正确！");
        } elseif (strlen($verify_code) != 4) {
            $this->ajax_return(FLAG_ERROR, "请您输入四位正确的数字验证码！");
        }

        /**手机号码是否唯一**/
        if (!$this->check_phone($phone_mob)) {
            $this->ajax_return(FLAG_ERROR, '手机号码已经存在！');
        }

        /**获取手机短信日志信息**/
        $info = $this->get_sms_logs_info($phone_mob);

        /**是否存在用户手机号码信息**/
        if (!$info['phone_mob']) {
            $this->ajax_return(FLAG_ERROR, '用户手机号码信息不存在！');
        }

        /**验证码是否一致**/
        if ($verify_code != $info['verify_code']) {
            $this->ajax_return(FLAG_ERROR, '短信验证码不正确，请您重新输入！');
        }

        /**验证码时间是否超过半个小时**/
        if ((time() - $info['created_at']) > 1800) {
            $this->ajax_return(FLAG_ERROR, '短信验证码已经超时，请您重新获取！');
        }

        $model = m('member');
        //修改手机号
        $sql = "UPDATE ".DB_PREFIX."member SET phone_mob=".$phone_mob." WHERE user_id=".$user_id;
        $flag = $model->query($sql);
        if ($flag) {
            $this->ajax_return(FLAG_OK,'修改手机号成功！');
        } else {
            $this->ajax_return(FLAG_ERROR, '修改手机号失败！');
        }
    }

    /**
     * 修改用户名
     * @author lz
     * @date 2016-1-6
     */
    public function editUsername(){
        $action = '修改用户名';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }

        /* 取得列表数据 */
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！');
        }

        $username = $this->get_gp('username', 'P');

        /**用户名不能为空**/
        if (!$username) {
            $this->ajax_return(FLAG_ERROR, "用户名不能为空！");
        }

        /**用户名是否唯一**/
        if (!$this->check_username($username)) {
            $this->ajax_return(FLAG_ERROR, '用户名已经存在！');
        }

        $model = m('member');
        //修改手机号
        $sql = "UPDATE ".DB_PREFIX."member SET user_name='".addslashes($username)."' WHERE user_id=".$user_id;
        $flag = $model->query($sql);
        if ($flag) {
            $this->ajax_return(FLAG_OK,'修改用户名成功！');
        } else {
            $this->ajax_return(FLAG_ERROR, '修改用户名失败！');
        }
    }

    /**
     * 修改职业名称
     * @author lz
     * @date 2016-1-6
     */
    public function editProfession(){
        $action = '修改职业名称';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }

        /* 取得列表数据 */
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！');
        }

        $profession = $this->get_gp('profession', 'P');

        /**职业名称不能为空**/
        if (!$profession) {
            $this->ajax_return(FLAG_ERROR, "职业名称不能为空！");
        }

        $model = m('member');
        //修改职业
        $sql = "UPDATE ".DB_PREFIX."member SET profession='".addslashes($profession)."' WHERE user_id=".$user_id;
        $flag = $model->query($sql);
        if ($flag) {
            $this->ajax_return(FLAG_OK,'修改职业成功！');
        } else {
            $this->ajax_return(FLAG_ERROR, '修改职业失败！');
        }
    }

    /**
     * 修改个人描述
     * @author lz
     * @date 2016-1-6
     */
    public function editDescription(){
        $action = '修改个人描述';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }

        /* 取得列表数据 */
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！');
        }

        $description = $this->get_gp('description', 'P');

        /**个人描述不能为空**/
        if (!$description) {
            $this->ajax_return(FLAG_ERROR, "个人描述不能为空！");
        }

        $model = m('member');
        //个人描述
        $sql = "UPDATE ".DB_PREFIX."member SET description='".addslashes($description)."' WHERE user_id=".$user_id;
        $flag = $model->query($sql);
        if ($flag) {
            $this->ajax_return(FLAG_OK,'修改个人描述成功！');
        } else {
            $this->ajax_return(FLAG_ERROR, '修改个人描述失败！');
        }
    }

    /**
     * 修改个人生日
     * @author lz
     * @date 2016-1-6
     */
    public function editBirthday(){
        $action = '修改个人生日';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }

        /* 取得列表数据 */
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！');
        }

        $birthday = $this->get_gp('birthday', 'P');

        /**生日不能为空**/
        if (!$birthday) {
            $this->ajax_return(FLAG_ERROR, "生日不能为空！");
        }

        $model = m('member');
        //修改生日
        $sql = "UPDATE ".DB_PREFIX."member SET birthday='".addslashes($birthday)."' WHERE user_id=".$user_id;
        $flag = $model->query($sql);
        if ($flag) {
            $this->ajax_return(FLAG_OK,'修改生日成功！');
        } else {
            $this->ajax_return(FLAG_ERROR, '修改生日失败！');
        }
    }

    /**
     * 修改性别
     * @author lz
     * @date 2016-1-6
     */
    public function editGender(){
        $action = '修改性别';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }

        /* 取得列表数据 */
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！');
        }
        // 0女 1男 2保密
        $gender = $this->get_gp('gender', 'P');

        /**验证性别**/
        if (strlen($gender) != 1) {
            $this->ajax_return(FLAG_ERROR, "请选择正确的性别！");
        } elseif (!$this->is_number($gender)) {
            $this->ajax_return(FLAG_ERROR, "请选择正确的性别！");
        }

        $model = m('member');
        //修改性别
        $sql = "UPDATE ".DB_PREFIX."member SET gender=".$gender." WHERE user_id=".$user_id;
        $flag = $model->query($sql);
        if ($flag) {
            $this->ajax_return(FLAG_OK,'修改性别成功！');
        } else {
            $this->ajax_return(FLAG_ERROR, '修改性别失败！');
        }
    }

    /**
     * 上传背景图片
     * @author lz
     * @date 2016-1-6
     */
    public function uploadBanner() {
        $action = '修改性别';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $config = require ROOT_PATH . '/data/config.qiniu.php';
        $user_id = $this->get_gp('user_id', 'P');
        $user_id = $user_id ? intval($user_id) : 0;
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您登陆！');
        }
        $file = $_FILES['file'];
        if ($file['error'] != UPLOAD_ERR_OK) {
            $this->ajax_return(FLAG_ERROR, '上传图片错误！');
        }
        import('uploader.lib');
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->addFile($file);

        //获取原来的头像信息
        $model = m('member');
        $info = $model->get(array(
            'conditions'    => "user_id={$user_id}",
            'fields'        => 'banner',
        ));
        //七牛云上传图片
        $filename = $uploader->random_filename();
        $filename = 'data/files/mall/memberbanner/'.date('Y').'/'.date('m').'/'.date('d').'/'.$filename.$user_id.'.jpg';
        if (!is_dir(dirname($filename))) {
            $res = @mkdir(dirname($filename), 0777, true);
            if ($res === false) {
                $this->ajax_return(FLAG_ERROR, '创建目录失败!');
            }
        }
        $rs = @move_uploaded_file($file['tmp_name'], ROOT_PATH.'/'.$filename);
        if ($rs === false) {
            $this->ajax_return(FLAG_ERROR, '移动图片失败!');
        }
        //更新头像信息
        $flag = $model->edit($user_id, array('banner'=>$filename));
        if ($flag === false) {
            @unlink(ROOT_PATH.'/'.$filename);//如果上传不成功，则删除刚上传的头像
            $this->ajax_return(FLAG_ERROR, '更新背景数据信息失败');
        }
        //删除旧的头像图片
        @unlink(ROOT_PATH.'/'.$info['banner']);
        $this->ajax_return(FLAG_OK, '', array('banner'=>$config['qiniu_url'].$filename));
    }

    /**
     * 根据手机号获取用户信息
     * @param $phone_mob
     * @return array
     * @author jiayanxiu
     * @date 2015/01/09
     */
    private function get_member_info_by_phone($phone_mob) {
        $model = m('member');
        $info = $model->get("phone_mob='{$phone_mob}'");
        return $info;
    }

    /**
     * 根据用户名或手机号获取用户信息
     * @param $content
     * @return array
     * @author jiayanxiu
     * @date 2015-01-09
     */
    private function get_member_info($content) {
        $model = m('member');
        $info = $model->get("user_name='{$content}' or phone_mob='{$content}'");
        return $info;
    }

    /**
     * 根据用户ID获取用户信息
     * @param $id
     * @return array
     * @author mingyang.sun
     * @date 2015-02-24
     */
    private function get_member_info_by_id($id) {
        return m('member')->get("user_id='{$id}'");
    }

    /**
     * 查看某个用户的主页
     * @author mingyang.sun
     * @date 2016-02-24
     */
    public function viewInfo (  )
    {
        $action = '查看某个用户的主页';
        setLogParameter($action);
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！');
        }
        $inquirer_id = $this->get_gp('user_id', 'G');
        $info =$this->get_member_info_by_id($inquirer_id);
        $model=m('member');
        $snum = $model->getSnum($this->get_gp('user_id', 'G'));
        $tnum = $model->getShow($this->get_gp('user_id', 'G'));
        $lnum = $model->getLnum($this->get_gp('user_id', 'G'));
        if ($info) {
            $data['user_id'] = $info['user_id'];
            $data['user_name'] = $info['user_name'];
            $data['portrait'] = $info['portrait']?QINIU_URL.$info['portrait']:'';
            $data['banner'] = $info['banner']?QINIU_URL.$info['banner']:'';
            $data['profession'] = $info['profession'];
            $data['description'] = $info['description'];
            $data['is_follow']=m('follow')->isFollow ($user_id,$info['user_id'])?'1':'0';
            $data['fans'] = $info['fan'];
            $data['follows'] = $info['follow'];
            $data['snum'] = $snum;
            $data['tnum'] = $tnum;
            $data['lnum'] = $lnum;
            $this->ajax_return(FLAG_OK,"",array($data));
        } else {
            $this->ajax_return(FLAG_ERROR, '获取用户信息失败！');
        }
    }

    /**
     * 关注某个用户
     * @author mingyang.sun
     * @date 2016-02-25
     */
    public function follow (  )
    {
        $action = '关注某个用户';
        setLogParameter($action);
        $user_id = $this->check_method('POST')->check_login();
        $fan_id = $follow_id = $this->get_gp('user_id', 'P');
        if ( $user_id == $follow_id ) $this->ajax_return(FLAG_ERROR, '不能关注自己');
        $follow = m ( 'follow' );
        // 关注过
        if ( $follow->isFollow ( $user_id,$follow_id ) ){
            $this->ajax_return(FLAG_ERROR, '已关注');
        }
        // 我(user_id) 关注 谁(follow_id)
        $follow->addFollow ( $user_id,$follow_id );
        // 我的关注数+1
        m('member')->increment($user_id,'follow');
        // 我 (user_id) 成为 谁(fans_id)的粉丝
        m ( 'fan' )->addFan ($user_id,$fan_id );
        // 谁的粉丝数+1
        m('member',array(),true)->increment($fan_id,'fan');
        $this->ajax_return(FLAG_OK,'关注成功！');
    }

    /**
     * 取消关注某个用户
     * @author mingyang.sun
     * @date 2016-02-25
     */
    public function unFollow (  )
    {
        $action = '取消关注某个用户';
        setLogParameter($action);
        $user_id = $this->check_method('POST')->check_login();
        $fan_id = $follow_id = $this->get_gp('user_id', 'P');
        if ( $user_id == $follow_id ) $this->ajax_return(FLAG_ERROR, '未关注对方');
        $follow = m ( 'follow' );
        // 关注过
        if ( ! $follow->isFollow ( $user_id,$follow_id ) ) {
            $this->ajax_return(FLAG_ERROR, '未关注');
        }
        // 我(user_id) 取消关注 谁(follow_id)
        $follow->unFollow ( $user_id,$follow_id );
        // 我的关注数-1
        m('member')->decrement($user_id,'follow');
        // 我 (user_id) 取消成为 谁(fans_id)的粉丝
        m ( 'fan' )->unFan ($user_id,$fan_id );
        // 谁的粉丝数-1
        m('member',array(),true)->decrement($fan_id,'fan');
        $this->ajax_return(FLAG_OK,'取消关注成功！');
    }

    /**
     * 粉丝列表
     */
    public function fans (  )
    {
        $action = '粉丝列表';
        setLogParameter($action);
        $self_id = $this->check_method()->check_login();
        if ( ! $user_id = $this->get_gp('user_id', 'G') ) $user_id = $self_id;
        // 我的粉丝ID列表
        $size = $this->get_gp('size', 'G')?intval($this->get_gp('size', 'G')):10;
        $ids = m( 'fan' )->getFanIds ( $user_id, $this->get_gp('page', 'G')?intval($this->get_gp('page', 'G')):0,$size);
        if ( ! $ids )$this->ajax_return(FLAG_ERROR,'没有粉丝！');
        $follows_ids = m('follow')->getFollowByFollowId ( $self_id,$ids );      //获取我关注的
        $intersect = array_intersect($ids, $follows_ids);                       //判断交集
        $this->handleRelationResponse($ids, $intersect);
    }

    /**
     * 关注列表
     * @author mingyang.sun
     * @date 2016-02-25
     */
    public function follows (  )
    {
        $action = '关注列表';
        setLogParameter($action);
        $user_id = $this->check_method()->check_login();
        if ( $this->get_gp('user_id', 'G') ) $user_id = $this->get_gp('user_id', 'G');
        $size = $this->get_gp('size', 'G')?intval($this->get_gp('size', 'G')):10;
		$ids = m( 'follow' )->getFollowIds ( $user_id, $this->get_gp('page', 'G')?intval($this->get_gp('page', 'G')):0,$size);
        if ( ! $ids )$this->ajax_return(FLAG_ERROR,'未关注！');
        $this->handleRelationResponse($ids);
    }

    protected function handleRelationResponse ( $ids, $intersect = array() )
    {
        if ( $userInfos  = m('member')->getInByUserId ($ids) )
        {
            foreach ( $userInfos as $index => $userInfo )
            {
                $datas[$index]['user_id'] = $userInfo['user_id'];
                $datas[$index]['user_name'] = $userInfo['user_name'];
                $datas[$index]['portrait'] = $userInfo['portrait']?QINIU_URL.$userInfo['portrait']:'';
                $datas[$index]['profession'] = $userInfo['profession'];
                $datas[$index]['description'] = $userInfo['description'];
                $datas[$index]['is_star']= $userInfo['is_star']?1:0;
                $datas[$index]['is_follow'] = in_array ($userInfo['user_id'],$intersect);
            }
            $this->ajax_return(FLAG_OK,'',$datas);
        }
        $this->ajax_return(FLAG_ERROR,'用户不存在');

    }

    /**
     * 获取手机短信日志信息
     * @param $phone_mob
     * @return mixed
     * @author jiayanxiu
     * @date 2015-01-11
     */
    private function get_sms_logs_info($phone_mob) {
        $start = strtotime(date('Y-m-d 00:00:00'));
        $end = strtotime(date('Y-m-d 23:59:59'));
        $model = m('smslogs');
        $info = $model->get(array('conditions'=>"phone_mob={$phone_mob}",'order'=>'sms_id DESC','limit'=>1));
        $row = $model->get(array(
            'fields'=>'COUNT(*) AS count',
            'conditions'=>"phone_mob={$phone_mob} AND created_at > {$start} AND created_at <= {$end}",
        ));
        $info['count'] = $row['count'];
        return $info;
    }

    /**
     * 检查用户名是否唯一
     * @param $user_name
     * @return boolean
     * @author jiayanxiu
     * @date 2015/01/08
     */
    private function check_username($user_name) {
        $model_member = m('member');
        $info = $model_member->get("user_name='{$user_name}'");
        if ($info['user_name']) {
            return false;
        }

        return true;
    }

    /**
     * 检查手机号码是否唯一
     * @param $phone_mob
     * @return boolean
     * @author jiayanxiu
     * @date 2015/01/08
     */
    private function check_phone($phone_mob) {
        $model_member = m('member');
        $info = $model_member->get("phone_mob='{$phone_mob}'");
        if ($info['phone_mob']) {
            return false;
        }

        return true;
    }


    private function check_login (  )
    {
        $id =$this->checkLogin();
        if(0===$id){
            $this->ajax_return(ERROR_LOGIN, '用户没有登录！',array('user_id',0));
        }
        return $id;
    }
}